import React, { useState } from 'react';
import { Upload, Button, App } from 'antd';
import type { UploadProps } from 'antd';

interface PlaceholderWidgetProps {
  backgroundImage?: string;
  onImageChange?: (imageUrl: string) => void;
}

const PlaceholderWidget: React.FC<PlaceholderWidgetProps> = ({ 
  backgroundImage, 
  onImageChange 
}) => {
  const [uploading, setUploading] = useState(false);
  const { message } = App.useApp();

  const uploadProps: UploadProps = {
    name: 'file',
    accept: 'image/*',
    showUploadList: false,
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件！');
        return false;
      }
      
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB！');
        return false;
      }

      setUploading(true);
      
      // 创建本地预览URL
      const reader = new FileReader();
      reader.onload = (e) => {
        const imageUrl = e.target?.result as string;
        onImageChange?.(imageUrl);
        setUploading(false);
        message.success('背景图片上传成功！');
      };
      reader.readAsDataURL(file);
      
      return false; // 阻止自动上传
    },
  };

  return (
    <div 
      className="h-full w-full relative overflow-hidden rounded-2xl bg-cover bg-center bg-no-repeat"
      style={{
        backgroundImage: backgroundImage ? `url(${backgroundImage})` : 'none',
        backgroundColor: backgroundImage ? 'transparent' : '#f5f5f5'
      }}
    >
      {!backgroundImage ? (
        <div className="h-full flex flex-col items-center justify-center border-2 border-dashed border-gray-300 rounded-2xl">
          <i className="i-mdi-image text-4xl text-gray-400 mb-2" />
          <div className="text-sm text-gray-500 mb-3">上传图片</div>
          <Upload {...uploadProps}>
            <Button 
              type="primary" 
              size="small" 
              loading={uploading}
              icon={<i className="i-mdi-upload" />}
            >
              {uploading ? '上传中...' : '选择图片'}
            </Button>
          </Upload>
        </div>
      ) : (
        <div className="absolute inset-0 bg-black bg-opacity-30 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity duration-200 rounded-2xl">
          <Upload {...uploadProps}>
            <Button 
              type="primary" 
              size="small" 
              loading={uploading}
              icon={<i className="i-mdi-camera" />}
            >
              更换图片
            </Button>
          </Upload>
        </div>
      )}
    </div>
  );
};

export default PlaceholderWidget;